package cn.stylefeng.guns.modular.weixin.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.chanjar.weixin.mp.builder.kefu.ImageBuilder;
import me.chanjar.weixin.mp.builder.kefu.TextBuilder;
import org.springframework.stereotype.*;
import cn.stylefeng.guns.modular.system.service.*;
import org.springframework.beans.factory.annotation.*;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.common.session.*;
import me.chanjar.weixin.mp.bean.message.*;
import me.chanjar.weixin.mp.builder.kefu.*;
import me.chanjar.weixin.mp.bean.kefu.*;
import me.chanjar.weixin.common.error.*;
import me.chanjar.weixin.mp.builder.outxml.*;
import com.github.binarywang.utils.qrcode.*;
import cn.stylefeng.roses.core.util.*;
import org.apache.commons.io.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
import java.awt.*;
import org.apache.commons.lang3.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import me.chanjar.weixin.mp.bean.result.*;
import me.chanjar.weixin.common.bean.result.*;
import cn.stylefeng.guns.modular.system.entity.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.*;
import java.util.*;
import java.util.concurrent.*;

@Component
public class MenuHandler extends AbstractHandler
{
    public static Map<String, String> querySessionMap;
    @Autowired
    private DictService dictService;
    
    public WxMpXmlOutMessage handle(final WxMpXmlMessage wxMessage, final Map<String, Object> context, final WxMpService weixinService, final WxSessionManager sessionManager) {
        final String msg = String.format("type:%s, event:%s, key:%s", wxMessage.getMsgType(), wxMessage.getEvent(), wxMessage.getEventKey());
        if ("view".equals(wxMessage.getEvent())) {
            return null;
        }
        final String eventKey = wxMessage.getEventKey();
        final String fromUser = wxMessage.getFromUser();
        String returnMsg = "";
        if(StringUtils.equalsIgnoreCase(eventKey,"q1001_userinfo")){
            WechatUser user = this.wechatUserService.findByOpenId(fromUser);
            if(user!=null){
                returnMsg = String.format("用户编号：%s\n环保金：%.2f",user.getUserNo(),user.getWithdraw());
            }
        }
        return WxMpXmlOutMessage.TEXT().content(returnMsg).fromUser(wxMessage.getToUser()).toUser(fromUser).build();
    }
    
    private String createQrcode(final String qrcodeContent) {
        final byte[] qrcode = QrcodeUtils.createQrcode(qrcodeContent, 342, (File)null);
        final File qrcodeSaveFile = new File(ToolUtil.getWebRootPath("/upload/qrcode"), UUID.randomUUID().toString() + ".jpg");
        try {
            IOUtils.write(qrcode, (OutputStream)new FileOutputStream(qrcodeSaveFile));
            final File qrcodeBgFile = new File(ToolUtil.getWebRootPath("/upload/qrcode"), "qrcode_gb.jpg");
            final BufferedImage qrcodeBgImg = ImageIO.read(qrcodeBgFile);
            final BufferedImage qrcodeImg = ImageIO.read(qrcodeSaveFile);
            final int w = qrcodeImg.getWidth();
            final int h = qrcodeImg.getHeight();
            final Graphics2D g = qrcodeBgImg.createGraphics();
            g.drawImage(qrcodeImg, 189, 598, w, h, null);
            g.dispose();
            ImageIO.write(qrcodeBgImg, "jpg", qrcodeSaveFile);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return qrcodeSaveFile.getName();
    }
    
    private String getWXImgId(final WxMpXmlMessage wxMessage, final WxMpService weixinService) {
        final WechatUser user = this.getUser(wxMessage);
        String qrcodeImgPath = user.getQrcodeImgPath();
        File qrcodeSaveFile = null;
        if (StringUtils.isNotBlank((CharSequence)qrcodeImgPath)) {
            qrcodeSaveFile = new File(ToolUtil.getWebRootPath("/upload/qrcode"), qrcodeImgPath);
            if (!qrcodeSaveFile.exists()) {
                qrcodeImgPath = null;
            }
        }
        if (StringUtils.isBlank((CharSequence)qrcodeImgPath)) {
            try {
                if (StringUtils.isBlank((CharSequence)user.getQrcodeUrl())) {
                    final WxMpQrCodeTicket wxMpQrCodeTicket = weixinService.getQrcodeService().qrCodeCreateLastTicket(user.getId().toString());
                    user.setQrcodeCreateTime(new Date());
                    user.setQrcodeTicket(wxMpQrCodeTicket.getTicket());
                    user.setQrcodeUrl(wxMpQrCodeTicket.getUrl());
                }
                qrcodeImgPath = this.createQrcode(user.getQrcodeUrl());
                user.setQrcodeImgPath(qrcodeImgPath);
                user.insertOrUpdate();
            }
            catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        try {
            qrcodeSaveFile = new File(ToolUtil.getWebRootPath("/upload/qrcode"), qrcodeImgPath);
            WxMediaUploadResult res = null;
            res = weixinService.getMaterialService().mediaUpload("image", qrcodeSaveFile);
            final String mediaId = res.getMediaId();
            return mediaId;
        }
        catch (WxErrorException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private WechatUser getUser(final WxMpXmlMessage wxMessage) {
        final WechatUser user = this.wechatUserService.getByOpenId(wxMessage);
        return user;
    }
    
    private String getMsg(final String msgName, final Object... values) {
        final List<Dict> textList = this.dictService.selectByTypeCode("text_list");
        final Map<String, Dict> textMap = textList.stream().collect(Collectors.toMap(dict -> dict.getName(), dict -> dict));
        final Dict textDict = textMap.get(msgName);
        final String msgTemplate = textDict.getCode();
        return MsgHandler.parseMsgFormat(msgTemplate, values);
    }
    
    static {
        MenuHandler.querySessionMap = new ConcurrentHashMap<String, String>();
    }
}
